<?php
/**
 * Created by PhpStorm.
 * User: 王 朋
 * Date: 2018/4/19
 * Time: 22:12
 */
namespace application\admin\controller;
use application\common\controller\Base;
use think\exception\HttpException;
use application\common\model\SystemConfig;
use think\Session;
use application\common\controller\Util;

class Config extends Base
{
    public function index()
    {
        $systemConfig = new SystemConfig();
        $config = $systemConfig->where('system_id', 1)->select()[0];
        $this->assign([
            'active' => [4,41],
            'title' => '系统配置',
            'messageCount' => 0,
            'pageNum' => $config['perPageNum'],
            'threshold' => $config['startThreshold'],
            'minSize' => $config['minFileSize'],
            'maxSize' => $config['maxFileSize'],
            'isGrant' => $config['isGrantTeacher'],
        ]);
        return $this->fetch();
    }
    public function saveConfig() {
        if (! $this->request->isPost()) {
            throw new HttpException('403');
        }
        $pageNum = $this->request->post('pageNum');
        $threshold = $this->request->post('threshold');
        $minSize = $this->request->post('minSize');
        $maxSize = $this->request->post('maxSize');
        $isGrant = $this->request->post('isGrant');
        if (empty($pageNum) || empty($threshold) || empty($maxSize) || empty($isGrant)) {
            $this->error("请完善您的配置参数信息！",'index');
        } else if (!Util::str_is_int($pageNum) || !Util::str_is_int($threshold) || !Util::str_is_int($minSize) || !Util::str_is_int($maxSize) || !in_array($isGrant, array('yes', 'no'))) {
            $this->error('参数非法！', $_SERVER['HTTP_REFERER']);
        } else if ((int)$minSize <= 0) {
            $this->error(("上传文件大小应大于0字节"),'index');
        } else {
            $systemConfig = new SystemConfig();
            $systemConfig->save([
                'perPageNum' => $pageNum,
                'minFileSize' => $minSize,
                'maxFileSize' => $maxSize,
                'isGrantTeacher' => $isGrant == 'yes' ? '1' : '0',
                'startThreshold' => $threshold,
            ],['system_id' => 1]);
            Session::set('pageNum', $pageNum);
            $this->redirect('index/index');
        }
    }
}